package com.lz.zookeeper;

import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import com.lz.common.log4j.Log4jConfig;

/**
 * zookeeper 工具类
 * @author likejian
 * @date 2016-5-29 17:13:14
 */
public class ZooKeeperUtil {

	/**
	 * 创建节点
	 * @param zkClient
	 * @param path
	 * @param datas
	 * @param mode
	 * @return
	 * @throws Exception 
	 */
	public static String createNode(CuratorFramework zkClient, String path, byte[] datas, CreateMode mode) throws Exception{
		if(ZooKeeperUtil.checkExists(zkClient, path) == null){
			String result = zkClient.create()
					.creatingParentsIfNeeded()
					.withMode(mode)
					.forPath(path,datas);
			return result;
		}else{
			return path;
		}
	}
	
	/**
	 * 删除节点
	 * @param zkClient
	 * @param path
	 * @throws Exception
	 */
	public static void deleteNode(CuratorFramework zkClient, String path) throws Exception{
		zkClient.delete().guaranteed().deletingChildrenIfNeeded().withVersion(-1).forPath(path);
	}
	
	/**
	 * 获取子节点
	 * @param zkClient
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static List<String> getChildren(CuratorFramework zkClient, String path) throws Exception{
		List<String> cList = zkClient.getChildren().forPath(path);
		return cList;
	}
	
	/**
	 * 获取节点数据
	 * @param zkClient
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static String getData(CuratorFramework zkClient, String path) throws Exception{
		if(checkExists(zkClient, path) != null){
			byte[] configBytes = zkClient.getData().forPath(path);
			String configStr = new String(configBytes);
			return configStr;
		}
		return null;
	}
	
	/**
	 * 设置节点数据
	 * @param zkClient
	 * @param path
	 * @param datas
	 * @return
	 * @throws Exception
	 */
	public static Stat setData(CuratorFramework zkClient, String path, byte[] datas) throws Exception{
		Stat stat = new Stat();		
		zkClient.getData().storingStatIn(stat).forPath(path);
		return zkClient.setData().withVersion(stat.getVersion()).forPath(path, datas);
	}
	
	/**
	 * 检查节点是否存在
	 * @param zkClient
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static Stat checkExists(CuratorFramework zkClient, String path) throws Exception{
		Stat stat = new Stat();	
		stat = zkClient.checkExists().forPath(path);
		return stat;
	}
	
	/**
	 * 启动zkClient
	 * @param zkClient
	 * @param regValue
	 * @throws Exception 
	 */
	public static void startupZk(ZooKeeperClient zkClient, String regValue) throws Exception{
		zkClient.startup(regValue);
		// 启动log4j动态加载
		Log4jConfig.getInstance();
	}
	/**
	 * 关闭zkClient
	 * @param zkClient
	 */
	public static void shutdownZk(ZooKeeperClient zkClient){
		zkClient.shutdown();
	}
}
